package com.iot.ammeter.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @ClassName: CorsConfig
 * @Author: Basil
 * @Date: 2021/10/26 下午10:41
 * @Version: 1.0
 * @Description: 提供跨域支持
 **/
@Component
public class CorsConfig implements WebMvcConfigurer {
    @Value("${image.image-path}")
    private String imagePath;

    /**
     * 解决跨域问题
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    /**
     * 添加图片映射资源规则
     * @param registry 注册
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //外部访问路径
        registry.addResourceHandler("/img/**")
                //真实路径
                .addResourceLocations("file:" + imagePath);
    }
}
